package controllers;

import helpers.ObjectifyServiceHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.Domain;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class BlacklistDomainServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String domainName = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		Cache cache=null;
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
		
        Domain domain = new Domain();
        if(domainName!=null&&domainName.length()>0 && UrlHelper.checkDomain(domainName))
		{
			ObjectifyServiceHelper.register();
			Objectify ofy = ObjectifyService.begin();
			try {
				domain = ofy.get(new Key<Domain>(Domain.class, domainName));
				//domain = ofy.query(Domain.class).filter("name", domainName).get();
			} catch (Exception e) {
				response.getWriter().println("Domain hasn't exists in db.");
				return;
			}
			
			if (domain != null) {
			
				domain.setStatus(-1);
				ofy.put(domain);
				
				response.getWriter().println("Add success domain " + domainName + " to blacklist");
			}
		}
	}
}
